/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.simplenix.nicasio.misc;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author fronald
 */
public class ClassLoader extends URLClassLoader {

	private List<String> jarFilesPath = new ArrayList<String>();

	private List<String> classes = new ArrayList<String>();

	private List<String> classLoaded = new ArrayList<String>();

	private Map<String, Class> classesLoaded = new HashMap<String, Class>();

	public ClassLoader(URL[] urls) {
		super(urls);
	}

	public void addJarPath(String path) {
		this.jarFilesPath.add(path);
	}

	public void removeJarPath(String path) {
		this.jarFilesPath.remove(path);
	}

	public void addClassToLoad(String className) {
		this.classes.add(className);
	}

	public void removeClassToLoad(String className) {
		this.classes.remove(className);
	}

	private void addFiles(String path) throws MalformedURLException {
		String urlPath = "jar:file://" + path + "!/";
		addURL(new URL(urlPath));
	}

	public Class getLoadedClass(String name) {
		return this.classesLoaded.get(name);
	}

	public void loadClassesNow() throws MalformedURLException, ClassNotFoundException {
		for (String jarFile : this.jarFilesPath) {
			this.addFiles(jarFile);
		}
		for (String classe : this.classes) {
			if (!this.classLoaded.contains(classe)) {
				Class c = super.loadClass(classe);
				this.classesLoaded.put(classe, c);
				this.classLoaded.add(classe);
			}
		}
	}

}
